package net.organizer.ui.actionhandler;

import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;

import net.organizer.dao.Domain;
import net.organizer.dao.OrgPerson;

import org.json.JSONObject;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

public class OrgPersonPutInsertActionHandler extends ActionHandlerBase {
	private static final Logger logger = Logger.getLogger(OrgPersonPutInsertActionHandler.class.getName());
	
	private void logOrgPersons(String message, Objectify ofy, Domain domain, Long orgId){
		logger.fine(message);
		List<OrgPerson> orgPersons  = ofy.query(OrgPerson.class).ancestor(domain.getKey()).filter("orgId = ", orgId).order("personId").list();
		logger.fine(message + "...orgPersons.size(): " + orgPersons.size());
		for(OrgPerson orgPerson : orgPersons){
			logger.fine(String.format("orgPerson id: %d, orgId: %d, personId: %d ", orgPerson.getId(), orgPerson.getOrgId(), orgPerson.getPersonId()));
		}
	}

	@Override
	public void handleAction(HttpServletRequest req, JSONObject respJSONObject) throws Exception {
		logger.fine("handleAction");
		Long orgId = getParamValueAsLong(req, "orgId", true);
		logger.fine("<-------------   orgId: " + orgId);
		//Thread.sleep(10000);
		Domain domain = new Domain();
		domain.setName("domain1");
		List<OrgPerson> orgPersons = new LinkedList<OrgPerson>();
		Objectify ofy = ObjectifyService.beginTransaction();
		try {
			//this.logOrgPersons("before put...inside transaction", ofy, domain, orgId);
			if (req.getParameterValues("id") != null) {
				for (String value : req.getParameterValues("id")) {
					logger.finer(String.format("...parameter value: %s", value));
					Long personId = Long.parseLong(value);
					//keys.add(OrgPerson.getKey(domain, id));
					orgPersons.add(new OrgPerson(orgId, personId, domain));
				}
				logger.info(String.format("after load of http params... for put... orgPersons.size(): %d", orgPersons.size()));
			}else{
				logger.info(String.format("after load of http params... orgPersons.size() == 0"));
			}
			for(OrgPerson orgPerson : orgPersons){
				//logger.fine(String.format("about to put orgPerson id: %d, orgId: %d, personId: %d ", orgPerson.getId(), orgPerson.getOrgId(), orgPerson.getPersonId()));
			}
			ofy.put(orgPersons);
			//this.logOrgPersons("after put...inside transaction, before commit", ofy, domain, orgId);
			ofy.getTxn().commit();
		} finally {
			if (ofy.getTxn().isActive()) {
				ofy.getTxn().rollback();
			}
		}
		ofy = ObjectifyService.beginTransaction();
		//this.logOrgPersons("after put...after commit", ofy, domain, orgId);
		ofy.getTxn().commit();

	}
}
